const { asyncHandler } = require('../../middleware/errorHandler');
const { success, error, paginate, paginateResponse } = require('../../utils/common');
const { Op } = require('sequelize');
const Course = require('../../models/Course');
const logger = require('../../utils/logger');

class TeacherCourseController {
  /**
   * 教师课程列表
   */
  static index = asyncHandler(async (req, res) => {
    const { page = 1, limit = 10, status, title } = req.query;
    
    const where = { teacher_id: req.user.id };
    if (status) where.status = status;
    if (title) where.title = { [Op.like]: `%${title}%` };

    const { offset, limit: pageLimit } = paginate(page, limit);
    
    const { count, rows } = await Course.findAndCountAll({
      where,
      offset,
      limit: pageLimit,
      order: [['created_at', 'DESC']]
    });

    res.json(paginateResponse(rows, count, page, limit));
  });

  /**
   * 创建课程
   */
  static create = asyncHandler(async (req, res) => {
    const {
      title,
      description,
      cover,
      category_id,
      price,
      original_price,
      duration,
      lessons_count,
      is_free,
      is_recommend,
      is_hot,
      tags,
      requirements,
      objectives
    } = req.body;

    // 验证必填字段
    if (!title) {
      return res.status(400).json(error('课程标题为必填项'));
    }

    // 创建课程
    const course = await Course.create({
      title,
      description,
      cover,
      teacher_id: req.user.id,
      category_id,
      price: price || 0,
      original_price: original_price || 0,
      duration: duration || 0,
      lessons_count: lessons_count || 0,
      status: 'draft',
      is_free: is_free || false,
      is_recommend: is_recommend || false,
      is_hot: is_hot || false,
      tags: tags ? JSON.parse(tags) : [],
      requirements,
      objectives
    });

    logger.info(`教师 ${req.user.id} 创建课程: ${course.id}`);

    res.json(success(course, '课程创建成功'));
  });

  /**
   * 获取课程详情
   */
  static show = asyncHandler(async (req, res) => {
    const { id } = req.params;

    const course = await Course.findOne({
      where: { id, teacher_id: req.user.id }
    });

    if (!course) {
      return res.status(404).json(error('课程不存在'));
    }

    res.json(success(course, '获取成功'));
  });

  /**
   * 更新课程
   */
  static update = asyncHandler(async (req, res) => {
    const { id } = req.params;
    const updateData = req.body;

    const course = await Course.findOne({
      where: { id, teacher_id: req.user.id }
    });

    if (!course) {
      return res.status(404).json(error('课程不存在'));
    }

    // 更新课程
    await course.update(updateData);

    logger.info(`教师 ${req.user.id} 更新课程: ${id}`);

    res.json(success(null, '课程更新成功'));
  });

  /**
   * 删除课程
   */
  static delete = asyncHandler(async (req, res) => {
    const { id } = req.params;

    const course = await Course.findOne({
      where: { id, teacher_id: req.user.id }
    });

    if (!course) {
      return res.status(404).json(error('课程不存在'));
    }

    // 软删除
    await course.update({ status: 'archived' });

    logger.info(`教师 ${req.user.id} 删除课程: ${id}`);

    res.json(success(null, '课程删除成功'));
  });

  /**
   * 发布课程
   */
  static publish = asyncHandler(async (req, res) => {
    const { id } = req.params;

    const course = await Course.findOne({
      where: { id, teacher_id: req.user.id }
    });

    if (!course) {
      return res.status(404).json(error('课程不存在'));
    }

    await course.update({ status: 'published', published_at: new Date() });

    logger.info(`教师 ${req.user.id} 发布课程: ${id}`);

    res.json(success(null, '课程发布成功'));
  });

  /**
   * 下架课程
   */
  static unpublish = asyncHandler(async (req, res) => {
    const { id } = req.params;

    const course = await Course.findOne({
      where: { id, teacher_id: req.user.id }
    });

    if (!course) {
      return res.status(404).json(error('课程不存在'));
    }

    await course.update({ status: 'draft' });

    logger.info(`教师 ${req.user.id} 下架课程: ${id}`);

    res.json(success(null, '课程下架成功'));
  });

  /**
   * 获取课程统计
   */
  static stats = asyncHandler(async (req, res) => {
    const total = await Course.count({ where: { teacher_id: req.user.id } });
    const published = await Course.count({ where: { teacher_id: req.user.id, status: 'published' } });
    const draft = await Course.count({ where: { teacher_id: req.user.id, status: 'draft' } });
    const archived = await Course.count({ where: { teacher_id: req.user.id, status: 'archived' } });

    // 获取总学生数和总观看次数
    const totalStudents = await Course.sum('students_count', { where: { teacher_id: req.user.id } });
    const totalViews = await Course.sum('views_count', { where: { teacher_id: req.user.id } });

    res.json(success({
      total,
      published,
      draft,
      archived,
      totalStudents: totalStudents || 0,
      totalViews: totalViews || 0
    }, '获取成功'));
  });
}

module.exports = TeacherCourseController; 